package com.izhang3.proxy.channel;

import com.alibaba.fastjson.JSON;
import com.izhang3.proxy.config.ChannelTypeEnum;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.BoundListOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import java.util.*;
import java.util.concurrent.LinkedBlockingQueue;

/**
 * @author 张良
 * @desc
 * @since 2019/6/20 13:50
 */
@Component
public class ChannelService {

    @Autowired
    private RedisTemplate<String,String> redisTemplate;

    /**
     * 输出当前队列中的数据
     *
     * @param type
     * @return
     */
    public String data(ChannelTypeEnum type) {
       List<String> list = redisTemplate.boundListOps(type.getRedisKey()).range(0,-1);
       return JSON.toJSONString(list);
    }

    /**
     * 追加队列
     *
     * @param ips
     * @param type
     */
    public void addWaitList(List<String> ips, ChannelTypeEnum type) {
        BoundListOperations<String, String> ops= redisTemplate.boundListOps(type.getRedisKey());
        for(String ip:ips){
            ops.leftPush(ip);
        }
    }

    /**
     * 获取队列
     *
     * @param type
     */
    public List<String> getWaitList(ChannelTypeEnum type) {
        BoundListOperations<String, String> ops=
                redisTemplate.boundListOps(type.getRedisKey());
        Long size = ops.size();
        if(size<=0){
            return Collections.emptyList();
        }
        //最多获取10条
        int max = size > 10 ?10: size.intValue();
        List<String> ips = new ArrayList<>();
        for (int i = 0; i < max; i++) {
            ips.add(ops.rightPop());
        }
        return ips;
    }

    /**
     * 获取可用的IP列表
     *
     * @return
     */
    public String getIp() {
        BoundListOperations<String, String> ops=
                redisTemplate.boundListOps(ChannelTypeEnum.CHECK.getRedisKey());
        //队列为空数据
        Long size = ops.size();
        if(size >= 0){
            return "";
        }
        //获取一个随机值
        int s = new Random().nextInt(size.intValue());
        return ops.index(s);
    }
}
